//
//  CYBettingViewController.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/7/15.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "CYBettingViewController.h"
#import "CYShopCartViewController.h"
#import "CYBettingTitleView.h"
#import "CYBettingToolView.h"
#import "CYZhuDanSettingVC.h"
#import "CYBettingNumber.h"
#import "CYTrendViewController.h"
#import "CYBettingView.h"
#import "CYShopCartAuotCellHight.h"
#import "CYBetModel.h"
#import "CYCurrentBetModel.h"
#import "CYTrendView.h"
@interface CYBettingViewController ()

@property (nonatomic, strong) CYButton *titleBtn;//navigationbar的titleview
@property (nonatomic, strong) CYButton *trendBtn;//navigationbar的rightbtn
@property (nonatomic, strong) CYBettingTitleView *titleView;  //点击titleBtn 向下弹出投注方式选择
@property (nonatomic, strong) CYView *alphaView;//半透明背景
@property (nonatomic, strong) CYBettingToolView *toolview; //toolview,快速下注，添加注单
@property (nonatomic, strong) NSMutableDictionary *cart_selectDic;//添加注单，购彩车里的号码
@property (nonatomic, assign) NSUInteger firstIndex;  //选择的一级玩法
@property (nonatomic, assign) NSUInteger secondIndex;  //选择的二级玩法
@property (nonatomic, copy) NSString *bet_way_name;//玩法名字
@property (nonatomic, strong) CYZhuDanSettingVC *zhudanVC;//快速下单视图
@property (nonatomic, strong) NSDictionary *dict;//彩票的全部投注玩法信息
@property (nonatomic, strong) NSDictionary *current_dict;//当前彩票的投注玩法
@property (nonatomic, strong) NSMutableArray *bet_wayArr;//彩种的玩法数组
@property (nonatomic, strong) CYTrendView *trendView;//走势图
@property (nonatomic, strong) CYBettingView *betView;
@property (nonatomic, strong) CYBetModel *model;
@property (nonatomic, strong) CYCurrentBetModel *currentModel;
@end

@implementation CYBettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.toolview.hidden = NO;
    if (!_selectArr)
        self.selectArr = [NSMutableArray array];
    
}

- (CYButton *)titleBtn{
    if (!_titleBtn) {
        _titleBtn = [[CYButton alloc]initWithTitle:_bet_way_name titleColor:[UIColor whiteColor] titleSize:AL(17) Image:@"xlsjx"];
        [_titleBtn setImage:[UIImage imageNamed:@"slsjx"] forState:UIControlStateSelected];
        _titleBtn.imagePosition = RightPosition;
        [_titleBtn addTarget:self action:@selector(actionForTitleBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _titleBtn;
}

-  (CYBettingView *)betView{
    if (!_betView) {
        WS(self)
        _betView = [[CYBettingView alloc]initWithColor:[UIColor whiteColor] block:^(NSString *title, NSSet *set) {
            [weakSelf getBettingNumber:title set:set];
        } refresh:^{
            [weakSelf https];//倒计时结束，重新请求网络数据
        } headerBlock:^(NSString *headerTitle) {
            [weakSelf selectYaoYiYaoBtnOrShopCartBtn:headerTitle];
        }];
        if (self.selectArr.count > 0)
            _betView.randomArr = self.selectArr;
        [self.view addSubview:_betView];
        
        [_betView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).with.offset(NAVIBAR_HEIGHT + STATUS_HEIGHT);
            make.centerX.equalTo(self.view);
            make.bottom.equalTo(_toolview.mas_top).with.offset(0);
            make.width.mas_equalTo(SCREEN_WIDTH);
        }];
    }
    return _betView;
}

//走势图按钮
- (CYButton *)trendBtn{
    if (!_trendBtn) {
        _trendBtn = [[CYButton alloc]init];
        [_trendBtn setImage:[UIImage imageNamed:@"zoushiSwitch"] forState:UIControlStateNormal];
        [_trendBtn setImage:[UIImage imageNamed:@"zoushiSwitchRed"] forState:UIControlStateSelected];
        _trendBtn.bounds = CGRectMake(0.0, 0.0, AL(PT(90)), AL(PT(50)));
        [_trendBtn addTarget:self action:@selector(actionForSwitch:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _trendBtn;
}

- (CYBettingTitleView *)titleView{
    if (!_titleView) {
        WS(self)
        _titleView = [[CYBettingTitleView alloc]initWithColor:[UIColor whiteColor] withData:_bet_wayArr block:^(NSString *title, NSUInteger firstIndex, NSUInteger secondIndex) {
            if (_firstIndex != firstIndex || _secondIndex != secondIndex)
                [weakSelf selectBetway:firstIndex index:secondIndex];  //选择一级玩法，二级玩法，更改布局
            weakSelf.bet_way_name = title;
            weakSelf.firstIndex = firstIndex;
            weakSelf.secondIndex = secondIndex;
            weakSelf.alphaView.hidden = YES;
        }];
        [self.view addSubview:_titleView];
        
        [_titleView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.top.equalTo(self.view).with.offset(-_titleView.bounds.size.height);
            make.size.mas_equalTo(_titleView.bounds.size);
        }];
    }
    return _titleView;
}

- (CYView *)alphaView{
    if (!_alphaView) {
        _alphaView = [[CYView alloc]initWithColor:TEXT_GRAY_COLOR];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(actionForSigleTap)];
        [_alphaView addGestureRecognizer:tap];
        _alphaView.alpha = 0.6;
        _alphaView.hidden = YES;
        [self.view addSubview:_alphaView];
        
        [_alphaView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0));
        }];
    }
    return _alphaView;
}

- (CYBettingToolView *)toolview{
    if (!_toolview) {
        WS(self)
        _toolview = [[CYBettingToolView alloc]initWithColor:[UIColor whiteColor] line:LineTop lineColor:LINE_COLOR block:^(NSString *string) {
            [weakSelf actionForToolBtn:string];
        }];
        _toolview.lineWidth = 0.5;
        [self.view addSubview:_toolview];
        
        [_toolview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsMake(SCREEN_HEIGHT - _toolview.bounds.size.height, 0.0, 0.0, 0.0));
        }];
    }
    
    return _toolview;
}

- (CYZhuDanSettingVC *)zhudanVC{
    if (!_zhudanVC) {
        WS(self)
        self.alphaView.hidden = YES;
        _zhudanVC = [[CYZhuDanSettingVC alloc] initBlock:^(id zhuDanDic, BOOL isSuccess) {
            weakSelf.alphaView.hidden = YES;//隐藏背景半透明
            DeLog(@"zhudanArr  %@",zhuDanDic);
            if (zhuDanDic || isSuccess) {//如果购彩车的数量大于0，或者下单成功，
                [weakSelf setupBettingNumberAndMoney:0];//无论添加注单还是快速下注后，投注注数，和金额都要置为0
                [weakSelf.selectArr removeAllObjects];//重置选中的号码
                weakSelf.betView.shopNum += (int)((zhuDanDic)?[zhuDanDic[@"code"] count]:0);//购彩车的彩种信息
                weakSelf.betView.reset = YES;
                [weakSelf addDictToCartSelecDic:zhuDanDic];
                //购彩车里的号码
                [_zhudanVC mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo(AL(404));
                }];
            }
        }];
        [self.view addSubview:_zhudanVC];
        
        [_zhudanVC mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.top.equalTo(self.view.mas_bottom).with.offset(0);
            make.width.mas_equalTo(_zhudanVC.bounds.size.width);
            make.height.mas_equalTo(_zhudanVC.bounds.size.height);
        }];
    }
    return _zhudanVC;
}

//走势图
- (CYTrendView *)trendView{
    if (!_trendView) {
        _trendView = [[CYTrendView alloc]initWithBlock:nil];
        [self.view addSubview:_trendView];
        [_trendView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsMake(NAVIBAR_HEIGHT + STATUS_HEIGHT, 0, 0, 0));
        }];
    }
    return _trendView;
}

- (void)setModel:(CYBetModel *)model{
    if (_model != model) {
        _model = model;
        self.currentModel = [CYCurrentBetModel mj_objectWithKeyValues:[CYBettingWay getCurrentModel:_model firstIndex:_firstIndex secondIndex:_secondIndex]];
        self.bet_way_name = [NSString stringWithFormat:@"%@-%@",_currentModel.firstBetName, _currentModel.secondBetName];
        self.bet_wayArr = [CYBettingWay getBettingWay:_model.firstSubBetArr];//玩法数组
    }
}

- (void)setCurrentModel:(CYCurrentBetModel *)currentModel{
    if (_currentModel != currentModel)
        _currentModel = currentModel;
    self.betView.model = currentModel;
    self.zhudanVC.model = currentModel;
}

//玩法名字
- (void)setBet_way_name:(NSString *)bet_way_name{
    if (_bet_way_name != bet_way_name)
        _bet_way_name = bet_way_name;
    if (!_titleBtn)
        self.navigationItem.titleView = self.titleBtn;
    else{
        [_titleBtn setTitle:bet_way_name forState:UIControlStateNormal];
        [_titleBtn mas_updateConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(_titleBtn.bounds.size);
        }];
    }
}

- (void)setSelectArr:(NSMutableArray *)selectArr{
    if (_selectArr != selectArr) {
        _selectArr = selectArr;
        NSUInteger number = 0;
        if (!_currentModel)
            number = [CYBettingNumber getNumberForBetting:2 playedIdentifier:@"ssc" selectData:_selectArr];
        else
            number = [CYBettingNumber getNumberForBetting:_currentModel.playedGroupId playedIdentifier:_currentModel.playedTpl selectData:_selectArr];
        [self setupBettingNumberAndMoney:number];
    }
    
}

//添加注单选中的号码，添加到购物车的字典里
- (void)addDictToCartSelecDic:(NSMutableDictionary *)cart_selectDic{
    if (!cart_selectDic || [[cart_selectDic allKeys] count] < 1 )
        return;
    //插入一级玩法名称和二级玩法名称
    NSMutableDictionary *new_cart_selectDic = [CYShopCartAuotCellHight insertBetWay:cart_selectDic
                                                                      playGroupName:[_bet_way_name componentsSeparatedByString:@"-"][0]
                                                                           playName:[_bet_way_name componentsSeparatedByString:@"-"][1]];
    if (!self.cart_selectDic){
        self.cart_selectDic = [NSMutableDictionary dictionary];
        self.cart_selectDic = new_cart_selectDic;
    }
    else
        for (id subObj in new_cart_selectDic[@"code"]) {
            [_cart_selectDic[@"code"] insertObject:subObj atIndex:0];
        }
    
}
//显示投注数目与金额
- (void)setupBettingNumberAndMoney:(NSUInteger)number{
    WS(self)
    weakSelf.toolview.bettingNumber = [NSString stringWithFormat:@"%lu",(unsigned long)number];
    weakSelf.toolview.money = [NSString stringWithFormat:@"%lu",number * 2];
}

//投注数目
- (void)getBettingNumber:(NSString *)title set:(NSSet *)set{
    self.selectArr = [CYBettingNumber getSelectArrFrom:self.selectArr title:title set:(NSMutableSet *)set];
}

//
- (void)shakeArr:(NSMutableArray *)array{
    _betView.randomArr = array;
    
}
//用来判断随机选取的快三-二同单选是否跟已选中的重复，如果重复，则重新随机
- (NSMutableArray *)kuaiSanErTongDanXuan:(NSMutableArray *)array{
    if (_selectArr.count < 2)
        return array;
    else if (_selectArr.count == 1){
        _betView.reset = YES;
        return array;
    }
    NSString * num1 = [[[[array[0] allValues] firstObject] allObjects] firstObject];
    NSString * num2 = [[[[array[1] allValues] firstObject] allObjects] firstObject];
    NSString * num3 = [[[[_selectArr[0] allValues] firstObject] allObjects] firstObject];
    NSString * num4 = [[[[_selectArr[1] allValues] firstObject] allObjects] firstObject];
    
    if ([num1 isEqualToString:num3] || [num1 isEqualToString:num4] || [num2 isEqualToString:num3] || [num2 isEqualToString:num4] )
        return [self kuaiSanErTongDanXuan:[CYBettingNumber getRandomSource:_currentModel.playedGroupId playedIdentifier:_currentModel.playedTpl cellArr:_currentModel.cellArr]];
    else
        return array;
}
//添加注单／快速下注／机选按钮／响应事件
- (void)actionForToolBtn:(NSString *)string{
    [_zhudanVC mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(AL(404));
    }];
    
    if ([string isEqualToString:@"机选"]) {
        [self.selectArr removeAllObjects];//重置选中的号码
        if ([_currentModel.playedTpl isEqualToString:@"k3_2dx"]) {
            self.selectArr = [self kuaiSanErTongDanXuan:[CYBettingNumber getRandomSource:_currentModel.playedGroupId playedIdentifier:_currentModel.playedTpl cellArr:_currentModel.cellArr]];
            _betView.randomArr = self.selectArr;
        }
        else{
            self.selectArr = [CYBettingNumber getRandomSource:_currentModel.playedGroupId playedIdentifier:_currentModel.playedTpl cellArr:_currentModel.cellArr];
            _betView.randomArr = self.selectArr;
        }
    }
    else{
        if (![_toolview.bettingNumber isEqualToString:@"0"]) {
            self.alphaView.hidden = NO;
            self.zhudanVC.isBet = ([string isEqualToString:@"快速下注"])?YES:NO;
            self.zhudanVC.number = [_toolview.bettingNumber integerValue];
            NSString *actionData = [CYBettingNumber stringWithArray:self.selectArr playedIdentifier:_currentModel.playedTpl];
            if ([_currentModel.playedTpl isEqualToString:@"ssc_ts_h3"] || [_currentModel.playedTpl isEqualToString:@"k3_hz"]) {//时时彩-后三特殊号码
                NSArray *array = [actionData componentsSeparatedByString:@","];
                CGSize size = [@"万" sizeWithAttributes:@{NSFontAttributeName :[UIFont systemFontOfSize:AL(13)]}];
                NSUInteger row = ceil(array.count / 4.0);//行数
                CGFloat totalH = row * ceil(size.height);//总高度
                _zhudanVC.bounds = CGRectMake(_zhudanVC.bounds.origin.x, _zhudanVC.bounds.origin.y,_zhudanVC.bounds.size.width, _zhudanVC.bounds.size.height + totalH);
            }
            [self showTitleViewAndZhuDanVC];
            self.zhudanVC.actionData = actionData;
        }else
            [CYHUD show:@"请至少添加一注"];
    }
    
}

//进入走势图
- (void)actionForSwitch:(CYButton *)sender{
    sender.selected = !sender.selected;
    _trendView.hidden = !sender.selected;
    _betView.hidden = sender.selected;
    _trendView.lottery_name = _lottery_name;
    _trendView.lottery_id = _lottery_id;
}

//玩法按钮事件
- (void)actionForTitleBtn:(CYButton *)sender{
    sender.selected = !sender.selected;
    if (sender.selected)
        [self showTitleViewAndZhuDanVC];
    else
        [self hiddenTitleViewAndZhuDanVC];
}

//点击空白，隐藏投注选择，和半透明背景
- (void)actionForSigleTap{
    _titleBtn.selected = NO;
    
    [self hiddenTitleViewAndZhuDanVC];
}

//显示彩种选择视图
- (void)showTitleViewAndZhuDanVC{
    _alphaView.hidden = NO;
    if (_titleBtn.selected)//
        [self.titleView show];
    else{
        [_zhudanVC mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(_zhudanVC.bounds.size.height);
        }];
        [UIView animateWithDuration:0.3 animations:^{
            _zhudanVC.transform = CGAffineTransformMakeTranslation(0.0, -_zhudanVC.bounds.size.height);
        }];
    }
}

//隐藏彩种选择视图和注单视图
- (void)hiddenTitleViewAndZhuDanVC{
    [_zhudanVC mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(AL(404));
    }];
    [UIView animateWithDuration:0.3 animations:^{
        _titleView.transform = CGAffineTransformIdentity;
        _zhudanVC.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        _alphaView.hidden = YES;
    }];
}
//选择一级玩法，二级玩法，cell清除之前的布局 布局更改  //重置
- (void)selectBetway:(NSUInteger)firstIndex index:(NSUInteger)secondIndex{
    _betView.reset = YES;
    _titleBtn.selected = NO;
    self.currentModel = [CYCurrentBetModel mj_objectWithKeyValues:[CYBettingWay getCurrentModel:_model firstIndex:firstIndex secondIndex:secondIndex]];//当前的玩法下的信息
    [_selectArr removeAllObjects];//一级玩法，二级玩法更改时候，清空选中的号码
    _toolview.bettingNumber = @"0";
    _toolview.money = @"0";
}

//摇一摇机选，或者购彩车
- (void)selectYaoYiYaoBtnOrShopCartBtn:(NSString *)type{
    WS(self)
    if ([type isEqualToString:@"购彩车"]) {
        CYShopCartViewController *cartVC = [[CYShopCartViewController alloc]init];
        cartVC.firstBetIndex = _firstIndex;//一级玩法
        cartVC.secondBetIndex = _secondIndex;//二级玩法
        cartVC.lottery_id = _lottery_id;//彩票id
        cartVC.block = ^(NSUInteger number, NSMutableDictionary *selectDic) {
            weakSelf.betView.shopNum = (int)number;
            weakSelf.cart_selectDic = selectDic;
        };
        cartVC.currentBetModel = _currentModel;
        cartVC.model = [CYShopCartLotteryModel mj_objectWithKeyValues:_cart_selectDic];//所有准备放入购彩车的号码组
        [self.navigationController pushViewController:cartVC animated:YES];
    }
    else if ([type containsString:@"摇一摇"])
        [self performSelector:@selector(actionForToolBtn:) withObject:@"机选"];
    
}
#pragma mark - 摇一摇相关方法
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    [CYAudio playAlertWithResourceName:@"shake" ofType:@"wav"];
}


- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (event.subtype == UIEventSubtypeMotionShake && [[CYAudioManager shareCYAudioManager] openAlert])
        [self performSelector:@selector(actionForToolBtn:) withObject:@"机选"];
}

//请求彩种数据
- (void)https{
    if (!_lottery_id)
        return;
    self.task = [CYHttps POST:API_betIndex parameters:@{@"id":_lottery_id} showHUD:YES progress:nil success:^(id data) {
        self.model = [CYBetModel mj_objectWithKeyValues:data];
    } failure:^(id string) {
        //        self.dict = nil;
    }];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self https];
    self.trendView.hidden = YES;
}

//返回上层之前，先清空购物车
- (void)back{
    if ([_cart_selectDic[@"code"] count] > 0) {
        [CYAlert showInWindowWithTitle:@"注意" message:@"即将清除购物车所有订单，是否确定退出？" enterComplete:^{
            [_cart_selectDic removeAllObjects];
            [super popPreviousViewController];
        }];
    }
    else
        [super popPreviousViewController];
    
}

- (void)setupNavigationBarTintColor:(UIColor *)color{
    [super setupNavigationBarTintColor:color];
    self.navigationItem.titleView = self.titleBtn;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.trendBtn];
}

- (void)viewDidDisappear:(BOOL)animated{
    [_betView releaseTimer];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
